package com.ceadeal.auth.config.custom;

import com.ceadeal.auth.service.UserService;
import com.ceadeal.auth.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 功能描述: 获取登录账号的权限信息
 *
 * 作者: Yzw
 * 日期: 2017-03-02 11:22:06
 */
@Service
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    private UserService userService;

    /**
     * 功能描述: 实现UserDetailsService.loadUserByUsername()
     *
     * 作者: Yzw
     * 日期: 2017-03-02 10:54:03
     */
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        UserDetails userDetails = null;

        // 获取用户信息
        User user = userService.findByUserName(userName);

        if (user != null) {
            // 取得用户的权限
            Collection<GrantedAuthority> grantedAuthorities = getGrantedAuthorities(user);
            // 封装成spring security user
            userDetails = new CustomUserDetails(user, true, true, true, true, grantedAuthorities);
        }

        return userDetails;
    }

    /**
     * 功能描述: 获取登录账号的权限信息
     *
     * 作者: Yzw
     * 日期: 2017-03-02 10:53:56
     */
    private Set<GrantedAuthority> getGrantedAuthorities(User user) {
        Set<GrantedAuthority> set = new HashSet<>();
        // TODO:ZZQ 用户可以访问的资源名称（或者说用户所拥有的权限） 注意：必须"ROLE_"开头
        set.add(new SimpleGrantedAuthority("ROLE_USER"));
        return set;
    }
}
